<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/static/layuiadmin/layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list" style="padding: 20px 30px 0 0;">
    <input type="hidden" name="id" value="{$find.id}">
    <input type="hidden" name="pid" value="{$find.pid}">
    <div class="layui-form-item">
        <label class="layui-form-label">活动名称: </label>
        <div class="layui-input-inline">
            <input type="text" name="name" value="{$find.name}" lay-verify="required" placeholder="活动名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">活动封面</label>
        <div class="layui-input-inline">
            <input type="text" name="image" value="{$find.image}" lay-verify="required" placeholder="活动封面" autocomplete="off" class="layui-input">
        </div>
        <button style="float: left;" type="button" class="layui-btn" id="test">上传封面</button>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">活动背景</label>
        <div class="layui-input-inline">
            <input type="text" name="banner" value="{$find.banner}" placeholder="活动背景" autocomplete="off" class="layui-input">
        </div>
        <button style="float: left;" type="button" class="layui-btn" id="up">上传背景</button>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">参与次数: </label>
        <div class="layui-input-inline">
            <input type="text" name="num" value="{$find.num}" lay-verify="required|number" placeholder="每人最多参与次数" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">活动类型: </label>
        <div class="layui-input-block">
            <input type="radio" name="type" value="1" lay-filter="type" title="抽奖轮盘" {if condition="$find eq ''"}checked{/if}{eq name='find.type' value='1'}checked{/eq}>
            <input type="radio" name="type" value="2" lay-filter="type" title="刮刮卡" {eq name='find.type' value='2'}checked{/eq}>
            <input type="radio" name="type" value="3" lay-filter="type" title="砸金蛋" {eq name='find.type' value='3'}checked{/eq}>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">活动条件: </label>
        <div class="layui-input-block">
            <input type="radio" name="action" value="1" lay-filter="action" title="购买商品" {if condition="$find eq ''"}checked{/if}{eq name='find.action' value='1'}checked{/eq}>
            <input type="radio" name="action" value="2" lay-filter="action" title="消耗积分"{eq name='find.action' value='2'}checked{/eq}>
        </div>
    </div>
    <div id="action">
        <div class="layui-form-item">
            <label class="layui-form-label">活动商品: </label>
            <div class="layui-input-inline">
                <input type="text" value="{$find.p_name}" lay-verify="huo_shop" id="demo" ts-selected="{$find.pid}" placeholder="选择活动商品" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <label class="layui-form-label">消耗积分数: </label>
            <div class="layui-input-inline">
                <input type="text" name="consume" value="{$find.integral}" lay-verify="huo_consume" placeholder="消耗积分数" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div id="type">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">抽奖选项: </label>
                <div class="layui-input-inline" style="width: 100px;">
                    <button class="layui-btn layui-btn-normal layui-btn-sm" id="add">添加选项</button>
                </div>
                <div id="xuanxiang">

                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">活动简介: </label>
        <div class="layui-input-block">
            <script id="container" name="content" type="text/plain">
                {$find.content}
            </script>
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-submit" id="layuiadmin-app-form-submit" value="提交">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-edit" id="layuiadmin-app-form-edit" value="修改">
    </div>
</div>
<script src="/static/layuiadmin/layui/layui.js"></script>
<!-- 配置文件 -->
<script type="text/javascript" src="/static/UEditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="/static/UEditor/ueditor.all.js"></script>
<script>
    layui.config({
        version: true,
        base: '/static/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'tableSelect', 'draw', 'upload'], function(){
        var $ = layui.$,
                form = layui.form,
                upload = layui.upload,
                tableSelect = layui.tableSelect;

        //普通图片上传
        upload.render({
            elem: '#up'
            ,url: "{:url('Activity/upload2')}"
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                layer.msg('上传成功');
                $("input[name=banner]").val(res.img);
            }
        });

        //普通图片上传
        upload.render({
            elem: '#test'
            ,url: "{:url('Activity/upload2')}"
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                layer.msg('上传成功');
                $("input[name=image]").val(res.img);
            }
        });

        //编辑器
        var ue = UE.getEditor('container', {
            initialFrameWidth: 800,
            initialFrameHeight: 320
        });

        if ('{$find.action}'){
            var index = '{$find.action}' - 1;
            $("#action").find('.layui-form-item').eq(index).removeClass('layui-hide').siblings().addClass('layui-hide');
        }

        //如果是抽奖并且有选项的话把选项循环出来
        if ('{$find.type}' && '{$find.draw}'){
            var draw = JSON.parse('{$find.draw}');
            for (var i = 0; i < draw.length; i++){
                var song = [];
                var zhi = [];
                var img = [];
                var p_name = [];
                var hide = [];
                for (var z = 0; z < 4; z++){
                    song[z] = '';
                    zhi[z] = '';
                    img[z] = '';
                    p_name[z] = '';
                    hide[z] = 'layui-hide';
                }
                song[draw[i].song-1] = 'checked';
                zhi[draw[i].song-1] = draw[i].zhi;
                img[draw[i].song-1] = draw[i].img;
                p_name[draw[i].song-1] = draw[i].p_name;
                hide[draw[i].song-1] = '';
                $("#xuanxiang").append('<div class="layui-form-item xuanxiang">' +
                        '<div class="layui-block" style="margin-left: 110px;">' +
                        '<div class="layui-input-inline" style="width: 200px;">' +
                        '<input type="text" name="xuan-name" value="' + draw[i].name + '" lay-verify="required" placeholder="选项奖品名称" autocomplete="off" class="layui-input">' +
                        '</div>' +
                        '<div class="layui-input-inline" style="width: 200px;">' +
                        '<input type="text" name="xuan-chance" value="' + draw[i].chance + '" lay-verify="required|number" placeholder="选项概率(%)" autocomplete="off" class="layui-input">' +
                        '</div>' +
                        '<button class="layui-btn  layui-btn-danger layui-btn-sm del">删除</button>' +
                        '</div>' +
                        '<div class="layui-block" style="margin-top: 20px;margin-left: 110px;">' +
                        '<input type="text" name="img" value="' + draw[i].img + '" lay-verify="required" style="width: 300px;display: inline-block;" placeholder="选项图片" autocomplete="off" class="layui-input">' +
                        '<button style="margin-left: 15px;" type="button" class="layui-btn" id="up' + i + '">上传图片</button>' +
                        '</div>' +
                        '<div class="layui-block" style="margin-top: 10px;margin-left: 110px;">' +
                        '<input type="radio" name="song' + i + '" value="1" lay-filter="song" title="赠送积分"' + song[0] + '>' +
                        '<input type="radio" name="song' + i + '" value="2" lay-filter="song" title="赠送优惠券"' + song[1] + '>' +
                        '<input type="radio" name="song' + i + '" value="3" lay-filter="song" title="赠送礼包"' + song[2] + '>' +
                        '<input type="radio" name="song' + i + '" value="4" lay-filter="song" title="赠送商品"' + song[3] + '>' +
                        '<input type="radio" name="song' + i + '" value="5" lay-filter="song" title="无奖品"' + song[4] + '>' +
                        '</div>' +
                        '<div class="layui-inline song-input' + i + '" style="margin-top: 10px;margin-left: 110px;">' +
                        '<input type="text" name="integral" value="' + zhi[0] + '" lay-verify="huo_integral" data-name="song' + i + '" placeholder="赠送积分" autocomplete="off" class="layui-input ' + hide[0] + '">' +
                        '<input type="text" name="coupon_name" value="' + p_name[1] + '" ts-selected="' + zhi[1] + '" id="coupon' + i + '" lay-verify="huo_coupon" data-name="song' + i + '" placeholder="选择优惠券" autocomplete="off" class="layui-input ' + hide[1] + '">' +
                        '<input type="text" name="package_name" value="' + p_name[2] + '" ts-selected="' + zhi[2] + '" id="package' + i + '" lay-verify="huo_package" data-name="song' + i + '" placeholder="选择礼包" autocomplete="off" class="layui-input ' + hide[2] + '">' +
                        '<input type="text" name="shop_name" value="' + p_name[3] + '" ts-selected="' + zhi[3] + '" id="shop' + i + '" lay-verify="huo_shop2" data-name="song' + i + '" placeholder="选择商品" autocomplete="off" class="layui-input ' + hide[3] + '">' +
                        '<input type="hidden" name="coupon" value="' + zhi[1] + '">' +
                        '<input type="hidden" name="package" value="' + zhi[2] + '">' +
                        '<input type="hidden" name="shop" value="' + zhi[3] + '">' +
                        '</div>' +
                        '</div>');
                form.render();
                openSelect('coupon', '#coupon' + i);
                openSelect('package', '#package' + i);
                openSelect('shop', '#shop' + i);
                upImg('#up' + i);
            }
        }

        //生成IMG上传
        function upImg(demo){
            //普通图片上传
            upload.render({
                elem: demo
                ,url: '/admin/Activity/upload2'
                ,done: function(res){
                    //如果上传失败
                    if(res.code > 0){
                        return layer.msg('上传失败');
                    }
                    //上传成功
                    layer.msg('上传成功');
                    $(demo).prev().val(res.img);
                }
            });
        }

        //弹窗选择
        function openSelect(item, demo){
            var searchPlaceholder = '';
            var url = '';
            var cols = [[]];
            if (item === 'coupon'){
                searchPlaceholder = '搜索优惠券名称';
                url = '/admin/Product/coupon/status/2';
                cols = [[
                    {type: 'radio'},
                    {field: 'name', title: '优惠券名称', width: 400},
                    {field: 'discount', title: '价值', width: 100, templet: function(d){
                        if (d.form == '0'){
                            return d.discount + '元';
                        }else{
                            return '订单总价的' + d.discount + '折';
                        }
                    }},
                    {field: 'limit', title: '领取限制', width: 100, templet: function(d){
                        if (d.limit == '0'){
                            return '不限';
                        }else{
                            return '限领' + d.limit + '份';
                        }
                    }},
                    {field: 'valid', title: '有效期', width: 100, templet: function(d){
                        if (d.limit == '0'){
                            return '不限';
                        }else{
                            return '限领' + d.limit + '份';
                        }
                    }},
                    {field: 'receive', title: '已领取', width: 100},
                    {field: 'use', title: '已使用', width: 100},
                ]];
            } else if (item === 'package'){
                searchPlaceholder = '搜索大礼包名称';
                url = '/admin/Gift/package';
                cols = [[
                    {type: 'radio'},
                    {field: 'name', title: '大礼包名称', width: 400},
                    {field: 'start', title: '有效期', width: 300, templet: function (d){ return formatDateTime(d.start) + '-' + formatDateTime(d.end) }}
                ]];
            } else if (item === 'shop'){
                searchPlaceholder = '搜索商品名称';
                url = '/admin/Product/product';
                cols = [[
                    {type: 'radio'},
                    {field: 'name', title: '商品名称', width: 400},
                    {field: 'stock', title: '库存', width: 100},
                    {field: 'volume', title: '销量', width: 100},
                    {field: 'time', title: '添加时间', width: 200, templet: function(d){ return formatDateTime(d.time); }}
                ]];
            }
            tableSelect.render({
                elem: demo,	//定义输入框input对象
                checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
                searchKey: 'name',	//搜索输入框的name值 默认keyword
                searchPlaceholder: searchPlaceholder,	//搜索输入框的提示文字 默认关键词搜索
                table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                    url: url,
                    method: 'post',
                    cols: cols
                },
                done: function (elem, data) {
                    //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                    //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
                    var field = data.data;
                    $(demo).val(field[0].name);
                    $(demo).nextAll('input[name=' + item + ']').val(field[0].id);
                }
            });
        }

        tableSelect.render({
            elem: '#demo',	//定义输入框input对象
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'name',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '搜索商品名称',	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: '/admin/Product/product/is_jin/1',
                method: 'post',
                cols: [[
                    {type: 'checkbox'},
                    {field: 'name', title: '商品名称', width: 400},
                    {field: 'stock', title: '库存', width: 100},
                    {field: 'volume', title: '销量', width: 100},
                    {field: 'time', title: '添加时间', width: 200, templet: function(d){ return formatDateTime(d.time); }}
                ]]
            },
            done: function (elem, data) {
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
                var field = data.data;
                var pid = [];
                var name = [];
                for (var i = 0; i < field.length; i++){
                    pid.push(field[i].id);
                    name.push(field[i].name);
                }
                pid.join(',');
                name.join(',');
                $("input[name=pid]").val(pid);
                $("#demo").val(name);
            }
        });

        //添加
        form.on('submit(layuiadmin-app-form-submit)', function(data){
            var field = data.field;
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            var type = $("input[name=type]:checked").val();
            if (type){
                var xuan = $(".xuanxiang").length;
                if (xuan < 2) return layer.msg('抽奖选项最少为两项');
                var chance = 0;
                $("input[name=xuan-chance]").each(function (index){
                    chance += Number($(this).val());
                });
                if (chance != 100) return layer.msg('概率总和应为100%');
                field.xuan = [];
                $(".xuanxiang").each(function (index){
                    var name = $(this).find('input[name=xuan-name]').val(); //选项名称
                    var chance = $(this).find('input[name=xuan-chance]').val(); //选项概率
                    var img = $(this).find('input[name=img]').val(); //选项图片
                    var song = $(this).find('input[name=song' + index + ']:checked').val(); //赠送类型
                    var zhi = 0;
                    var p_name = '';
                    switch (song){
                        case '1':
                            zhi = $(this).find('input[name=integral]').val();
                            p_name = '';
                            break;
                        case '2':
                            zhi = $(this).find('input[name=coupon]').val();
                            p_name = $(this).find('input[name=coupon_name]').val();
                            break;
                        case '3':
                            zhi = $(this).find('input[name=package]').val();
                            p_name = $(this).find('input[name=package_name]').val();
                            break;
                        case '4':
                            zhi = $(this).find('input[name=shop]').val();
                            p_name = $(this).find('input[name=shop_name]').val();
                            break;
                        default:
                            zhi = $(this).find('input[name=integral]').val();
                            p_name = '';
                            break;
                    }
                    field.xuan.push({name: name, chance: chance, song: song, zhi: zhi, p_name: p_name, img: img});
                });
            }
            field.content = ue.getContent();
            $.post("{:url('Activity/activity_add')}", {field:field}, function(e){
                if (e.code == 200){
                    layer.msg(e.data, {icon: 1});
                    setTimeout(function () {
                        parent.layui.table.reload('demo'); //重载表格
                        parent.layer.close(index); //再执行关闭
                    }, 500)
                }else{
                    layer.msg(e.msg, {icon: 2});
                }
            }, 'json')
        });

        //修改
        form.on('submit(layuiadmin-app-form-edit)', function(data){
            var field = data.field;
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            var type = $("input[name=type]:checked").val();
            if (type){
                var xuan = $(".xuanxiang").length;
                if (xuan < 2) return layer.msg('抽奖选项最少为两项');
                var chance = 0;
                $("input[name=xuan-chance]").each(function (index){
                    chance += Number($(this).val());
                });
                if (chance != 100) return layer.msg('概率总和应为100%');
                field.xuan = [];
                $(".xuanxiang").each(function (index){
                    var name = $(this).find('input[name=xuan-name]').val(); //选项名称
                    var chance = $(this).find('input[name=xuan-chance]').val(); //选项概率
                    var img = $(this).find('input[name=img]').val(); //选项图片
                    var song = $(this).find('input[name=song' + index + ']:checked').val(); //赠送类型
                    var zhi = 0;
                    var p_name = '';
                    switch (song){
                        case '1':
                            zhi = $(this).find('input[name=integral]').val();
                            p_name = '';
                            break;
                        case '2':
                            zhi = $(this).find('input[name=coupon]').val();
                            p_name = $(this).find('input[name=coupon_name]').val();
                            break;
                        case '3':
                            zhi = $(this).find('input[name=package]').val();
                            p_name = $(this).find('input[name=package_name]').val();
                            break;
                        case '4':
                            zhi = $(this).find('input[name=shop]').val();
                            p_name = $(this).find('input[name=shop_name]').val();
                            break;
                        default:
                            zhi = $(this).find('input[name=integral]').val();
                            p_name = '';
                            break;
                    }
                    field.xuan.push({name: name, chance: chance, song: song, zhi: zhi, p_name: p_name, img: img});
                });
            }
            field.content = ue.getContent();
            $.post("{:url('Activity/activity_edit')}", {field:field}, function(e){
                if (e.code == 200){
                    layer.msg(e.data, {icon: 1});
                    setTimeout(function () {
                        parent.layui.table.reload('demo'); //重载表格
                        parent.layer.close(index); //再执行关闭
                    }, 500)
                }else{
                    layer.msg(e.msg, {icon: 2});
                }
            }, 'json')
        });
    });

    //php时间戳用js转换为yyyy-mm-dd
    function formatDateTime(timeStamp) {
        var date = new Date();
        date.setTime(timeStamp * 1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    }
</script>
</body>
</html>